<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { useSubmissionHook } from "./utils/hook";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";

import Delete from "@iconify-icons/ep/delete";
import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";
import Upload from "@iconify-icons/ep/upload";
import { useUserStoreHook } from "@/store/modules/user";
// TODO 这个导入声明好长  看看如何优化
import { CommonUtils } from "@/utils/common";
import SubmissionFormModal from "@/views/cafuc/submit/submission/submission-form-modal.vue";
import SubmissionDetailModal from "@/views/cafuc/submit/submission/submission-detail-modal.vue";
import EditPen from "@iconify-icons/ep/edit-pen";
import View from "@iconify-icons/ep/view";
import { SubmissionPageResponse } from "@/api/performance/submission";
import AddFill from "@iconify-icons/ri/add-circle-line";
import {
  getUserScoreRecordListApi,
  calculateUserScoreApi,
  type UserScoreRecordPageResponse
} from "@/api/performance/userScoreRecord";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";

/** 组件name最好和菜单表中的router_name一致 */
defineOptions({
  name: "submissionList"
});

const router = useRouter();
const userStore = useUserStoreHook();
const loginLogStatusList = userStore.dictionaryList["common.status"];
const currentUserId = computed(
  () => userStore.currentUserInfo?.userId as number | undefined
);
const currentUserInfo = computed(() => userStore?.currentUserInfo);

// 个人信息完整性检查
const isProfileComplete = computed(() => {
  const user = currentUserInfo.value;
  // 检查真实姓名（可能是nickName或nickname）
  const hasNickName = !!(user?.nickName || (user as any)?.nickname);
  return !!(
    hasNickName &&
    user?.phoneNumber &&
    user?.deptId
  );
});

const tableRef = ref();

const searchFormRef = ref();
const {
  searchFormParams,
  pageLoading,
  columns,
  dataList,
  pagination,
  timeRange,
  defaultSort,
  multipleSelection,
  mainCategoryOptions,
  subCategoryOptions,
  itemCategoryOptions,
  onSearch,
  onSortChanged,
  exportAllExcel,
  getSubmissionList,
  handleDelete,
  handleBulkDelete,
  handleBulkSubmit,
  handleMainCategoryChange,
  handleSubCategoryChange,
  isSubProject,
  handleSubmit,
} = useSubmissionHook();

const opType = ref<"add" | "update">("add");
const modalVisible = ref(false);
const opRow = ref<SubmissionPageResponse>();
function openDialog(type: "add" | "update", row?: SubmissionPageResponse) {
  // 新增时检查个人信息完整性
  if (type === "add" && !isProfileComplete.value) {
    ElMessageBox.confirm(
      "需要先补充个人信息才能使用此功能，是否前往个人中心？",
      "提示",
      {
        confirmButtonText: "前往",
        cancelButtonText: "取消",
        type: "warning"
      }
    )
      .then(() => {
        router.push("/global/user/profile");
      })
      .catch(() => {});
    return;
  }
  opType.value = type;
  opRow.value = row;
  modalVisible.value = true;
}

const detailModalVisible = ref(false);
const detailRow = ref<SubmissionPageResponse>();
function openDetailDialog(row: SubmissionPageResponse) {
  detailRow.value = row;
  detailModalVisible.value = true;
}

const scoreLoading = ref(false);
const refreshScoreLoading = ref(false);
const userScoreRecord = ref<UserScoreRecordPageResponse | null>(null);
const scoreDisplayItems = computed(() => {
  const record = userScoreRecord.value;
  if (!record) {
    return [];
  }
  const generalScore = Number(record.generalCourseScore ?? 0);
  const majorScore = Number(record.majorCourseScore ?? 0);
  const labScore = Number(record.labCourseScore ?? 0);
  const approvedTotalScore = Number(record.approvedTotalScore ?? 0);
  const approvedProjectScore = Math.max(
    approvedTotalScore - (generalScore + majorScore + labScore),
    0
  );
  return [
    {
      label: "已批准总分",
      value: approvedTotalScore,
      courseValue: generalScore + majorScore + labScore,
      projectValue: approvedProjectScore
    },
    {
      label: "待审核总分",
      value: record.pendingScore
    }
  ];
});

// 默认将查询条件的owner设置为当前登录用户
searchFormParams.owner = currentUserId.value;

async function loadUserScoreRecord() {
  const userId = currentUserId.value;
  if (!userId) {
    userScoreRecord.value = null;
    return;
  }
  scoreLoading.value = true;
  try {
    const { data } = await getUserScoreRecordListApi({
      userId,
      pageNum: 1,
      pageSize: 1
    });
    userScoreRecord.value = data?.rows?.[0] ?? null;
  } catch (error) {
    console.error(error);
    userScoreRecord.value = null;
  } finally {
    scoreLoading.value = false;
  }
}

function handleResetForm() {
  const formEl = searchFormRef.value;
  if (!formEl) return;
  formEl.resetFields();
  searchFormParams.beginTime = undefined;
  searchFormParams.endTime = undefined;
  searchFormParams.owner = currentUserId.value;
  onSearch();
}

function formatScore(value?: number) {
  if (value === null || value === undefined) {
    return "-";
  }
  const num = Number(value);
  if (Number.isNaN(num)) {
    return "-";
  }
  return num.toFixed(2);
}

async function handleRefreshScore() {
  const userId = currentUserId.value;
  if (!userId) {
    ElMessage.warning("当前没有可刷新分数的用户");
    return;
  }
  if (refreshScoreLoading.value) return;
  refreshScoreLoading.value = true;
  try {
    await calculateUserScoreApi(userId);
    await new Promise(resolve => setTimeout(resolve, 1000));
    await loadUserScoreRecord();
    ElMessage.success("分数刷新任务已提交");
  } catch (error) {
    console.error(error);
    ElMessage.error("刷新分数失败，请稍后重试");
  } finally {
    refreshScoreLoading.value = false;
  }
}

watch(
  currentUserId,
  (newUserId, oldUserId) => {
    searchFormParams.owner = newUserId;
    loadUserScoreRecord();
    if (
      (newUserId && newUserId !== oldUserId) ||
      (!newUserId && oldUserId)
    ) {
      onSearch();
    }
  },
  { immediate: true }
);

watch(
  () => pageLoading.value,
  newValue => {
    if (newValue === false && currentUserId.value) {
      loadUserScoreRecord();
    }
  }
);

// 定义审核级别选项
const auditLevelOptions = [
  { label: "非审核状态", value: 0 },
  { label: "待一审", value: 1 },
  { label: "待二审", value: 2 },
  { label: "待三审", value: 3 },
  { label: "已完成", value: 4 }
];

// 定义状态选项
const statusOptions = [
  { label: "待提交", value: "DRAFT" },
  { label: "审核中", value: "PENDING_AUDIT" },
  { label: "已驳回", value: "REJECTED" },
  { label: "已批准", value: "APPROVED" }
];


// 设置表格行的类名（用于标识项目负责人不等于得分人的行）
function getRowClassName({ row }: { row: SubmissionPageResponse }) {
  // 当项目负责人不等于得分人时，添加特殊样式类
  if (row.owner && row.creatorId && row.owner !== row.creatorId) {
    return "row-owner-different";
  }
  return "";
}

</script>

<template>
  <div class="main">
    
    <div class="score-summary">
      <el-skeleton v-if="scoreLoading" :rows="2" animated />
      <el-empty v-else-if="!userScoreRecord" description="暂无分数数据" />
      <el-descriptions v-else :column="3" border size="small">
        <el-descriptions-item
          v-for="item in scoreDisplayItems"
          :key="item.label"
          :label="item.label"
        >
          <div class="score-summary__value">
            <span>{{ formatScore(item.value) }}</span>
            <span
              v-if="
                item.courseValue !== undefined &&
                item.projectValue !== undefined
              "
              class="score-summary__detail"
            >
              （课程总分 {{ formatScore(item.courseValue) }}，项目分
              {{ formatScore(item.projectValue) }}）
            </span>
          </div>
        </el-descriptions-item>
        <el-descriptions-item >
          <el-button
            type="primary"
            :icon="useRenderIcon(Refresh)"
            :loading="refreshScoreLoading"
            @click="handleRefreshScore"
          >
            刷新分数
          </el-button>
        </el-descriptions-item>
      </el-descriptions>
    </div>
    <!-- 搜索栏 -->
    <el-form
      ref="searchFormRef"
      :inline="true"
      :model="searchFormParams"
      class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px]"
    >
    <el-form-item label="序号" prop="id">
        <el-input
          v-model="searchFormParams.id"
          placeholder="请输入序号"
          clearable
          class="!w-[100px]"
        />
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="searchFormParams.title"
          placeholder="请输入标题"
          clearable
          class="!w-[200px]"
        />
      </el-form-item>
      <el-form-item label="考核年度" prop="assessmentYear">
        <el-input
          v-model="searchFormParams.assessmentYear"
          placeholder="请输入考核年度"
          clearable
          class="!w-[200px]"
        />
      </el-form-item>

      <el-form-item label="状态：" prop="status">
        <el-select
          v-model="searchFormParams.status"
          placeholder="请选择状态"
          clearable
          class="!w-[180px]"
        >
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="主类别：" prop="mainCategory">
        <el-select
          v-model="searchFormParams.mainCategory"
          placeholder="请选择主类别"
          clearable
          class="!w-[180px]"
          @change="handleMainCategoryChange"
        >
          <el-option
            v-for="item in mainCategoryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="子类别：" prop="subCategory">
        <el-select
          v-model="searchFormParams.subCategory"
          placeholder="请选择子类别"
          clearable
          class="!w-[180px]"
          :disabled="!searchFormParams.mainCategory"
          @change="handleSubCategoryChange"
        >
          <el-option
            v-for="item in subCategoryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="项目类别：" prop="itemCategory">
        <el-select
          v-model="searchFormParams.itemCategory"
          placeholder="请选择项目类别"
          clearable
          class="!w-[180px]"
          :disabled="!searchFormParams.subCategory"
        >
          <el-option
            v-for="item in itemCategoryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="当前审核级别" prop="currentAuditLevel">
        <el-select
          v-model="searchFormParams.currentAuditLevel"
          placeholder="请选择当前审核级别"
          clearable
          class="!w-[200px]"
        >
          <el-option
            v-for="item in auditLevelOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon(Search)"
          :loading="pageLoading"
          @click="onSearch(tableRef)"
        >
          搜索
        </el-button>
        <el-button
          :icon="useRenderIcon(Refresh)"
        @click="handleResetForm"
        >
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 提示信息 -->
    <el-alert
      type="info"
      :closable="false"
      show-icon
      style="margin-bottom: 12px;"
    >
      <template #default>
        <span>提示：多人参与的子项目无法编辑、删除、提交、审核，需要操作在主项目里操作，子项目会自动进行对应的修改。</span>
      </template>
    </el-alert>


    <!-- table bar 包裹  table -->
    <PureTableBar title="绩效上报列表" :columns="columns" @refresh="onSearch">
      <!-- 表格操作栏 -->
      <template #buttons>
        <el-button
          type="primary"
          :icon="useRenderIcon(AddFill)"
          @click="openDialog('add')"
        >
          新增绩效上报
        </el-button>
        <el-button
          type="success"
          :icon="useRenderIcon(Upload)"
          @click="handleBulkSubmit(tableRef)"
        >
          批量提交
        </el-button>
 
       
      </template>
      <template v-slot="{ size, dynamicColumns }">
        <pure-table
          border
          ref="tableRef"
          align-whole="center"
          showOverflowTooltip
          table-layout="auto"
          :loading="pageLoading"
          :size="size"
          adaptive
          :data="dataList"
          :columns="dynamicColumns"
          :default-sort="defaultSort"
          :pagination="pagination"
          :paginationSmall="size === 'small' ? true : false"
          :row-class-name="getRowClassName"
          :header-cell-style="{
            background: 'var(--el-table-row-hover-bg-color)',
            color: 'var(--el-text-color-primary)'
          }"
          @page-size-change="getSubmissionList"
          @page-current-change="getSubmissionList"
          @sort-change="onSortChanged"
          @selection-change="
            rows => (multipleSelection = rows.map(item => item.id))
          "
        >
          <!-- 添加 title slot -->
          <template #title="{ row }">
            <el-button
              link
              type="primary"
              @click="openDetailDialog(row)"
            >
              {{ row.title }}
            </el-button>
          </template>
          <template #operation="{ row }">
            <!-- 子项目（项目负责人不等于得分人）不显示任何操作按钮 -->
            <template v-if="isSubProject(row)">
              <!-- 子项目不显示操作按钮 -->
            </template>
            <!-- 非创建者或状态为审核中/已批准时，仅显示详情 -->
            <el-button
              v-else-if="row.owner !== row.creatorId || row.status === 'PENDING_AUDIT' || row.status === 'APPROVED'"
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon(View)"
              @click="openDetailDialog(row)"
            >
              详情
            </el-button>
            <!-- 创建者且状态为待提交或已驳回时，显示编辑和删除按钮 -->
            <template v-else-if="row.owner === row.creatorId && (row.status === 'DRAFT' || row.status === 'REJECTED')">
              <el-button
                class="reset-margin"
                link
                type="primary"
                :size="size"
                :icon="useRenderIcon(EditPen)"
                @click="openDialog('update', row)"
              >
                编辑
              </el-button>
              <el-button
                class="reset-margin"
                link
                type="success"
                :size="size"
                :icon="useRenderIcon(Upload)"
                @click="handleSubmit(row, tableRef)"
              >
                提交
              </el-button>
              <!-- 删除按钮仅当状态为草稿(DRAFT)时展示 -->
              <el-popconfirm
                v-if="row.status === 'DRAFT'"
                :title="`是否确认删除编号为${row.id}的这条绩效上报`"
                @confirm="handleDelete(row)"
              >
                <template #reference>
                  <el-button
                    class="reset-margin"
                    link
                    type="danger"
                    :size="size"
                    :icon="useRenderIcon(Delete)"
                  >
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
            </template>
          </template>
        </pure-table>
      </template>
    </PureTableBar>

    <submission-form-modal
      v-model="modalVisible"
      :type="opType"
      :row="opRow"
      @success="onSearch"
    />

    <submission-detail-modal
      v-model="detailModalVisible"
      :row="detailRow"
    />
  </div>
</template>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}

.score-summary {
  margin-bottom: 12px;
  padding: 16px;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: var(--el-border-radius-base);
  background-color: var(--el-fill-color-blank);

  .score-summary__value {
    display: flex;
    align-items: baseline;
    gap: 8px;
    flex-wrap: wrap;
  }

  .score-summary__detail {
    font-size: 12px;
    color: var(--el-text-color-secondary);
  }

  :deep(.el-descriptions__label) {
    font-weight: 500;
    color: var(--el-text-color-primary);
  }

  :deep(.el-descriptions__content) {
    font-weight: 600;
    color: var(--el-color-primary);
  }
}

// 去掉单元格两边的边框线
:deep(.el-table) {
  td {
    border-left: none !important;
    border-right: none !important;
  }
  
  th {
    border-left: none !important;
    border-right: none !important;
  }
}

// 项目负责人不等于得分人的行样式（灰色标识）
:deep(.row-owner-different) {
  background-color: rgba(158, 158, 158, 0.1) !important;
  
  &:hover {
    background-color: rgba(158, 158, 158, 0.15) !important;
  }
}
</style>
